/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.jitengine.i18nresource;

import com.inspur.edp.i18n.resource.api.metadata.ResourceItem;
import com.inspur.edp.i18n.resource.api.metadata.ResourceMetadata;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.I18nResource;
import com.inspur.edp.lcm.metadata.api.entity.I18nResourceItem;
import com.inspur.edp.lcm.metadata.api.entity.I18nResourceItemCollection;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.formmetadata.service.FormMetadataService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 资源项管理
 */
public class GenerateResourceManager {
    /**
     * 生成资源项id
     *
     * @param id
     * @param prefix
     * @return
     */
    public static String generateResourceId(String id, String prefix) {
        if (StringUtility.isNullOrEmpty(prefix)) {
            return id;
        }
        return prefix.toLowerCase() + "_" + id;
    }


    public static void generateEnI18nResource(GspMetadata metadata, String baseFormPath,
                                              GeneratedI18nResourceList i18nResourceList,
                                              String baseFormRelativePath,
                                              String keyPrefix) {
        generateI18nResource(metadata, baseFormPath, i18nResourceList, baseFormRelativePath, keyPrefix, "en");
    }

    /**
     * 生成对应的资源列表
     *
     * @param metadata
     * @param i18nResourceList
     * @param keyPrefix        key前缀
     * @param language
     */
    @Deprecated
    public static void generateI18nResource(GspMetadata metadata, String baseFormPath,
                                            GeneratedI18nResourceList i18nResourceList,
                                            String baseFormRelativePath,
                                            String keyPrefix,
                                            String language) {
        generateI18nResource(metadata, baseFormPath, i18nResourceList, keyPrefix, language);
    }

    public static void generateI18nResource(GspMetadata metadata, String baseFormPath,
                                            GeneratedI18nResourceList i18nResourceList,
                                            String keyPrefix,
                                            String language) {
        try {
            List<I18nResource> resourceList = FormMetadataService.getBeanInstance().getFormResourceWithMetaData(metadata, language, baseFormPath);
            generateResourceList(i18nResourceList, keyPrefix, resourceList);
        } catch (Exception ex) {
            //排除掉找不到对应的资源文件的异常
            if (ex.getMessage() != null && !ex.getMessage().contains("Can't Find Metadata")) {
                WebLogger.Instance.info(ex.getMessage(), GenerateResourceManager.class.getName());
            } else {
                WebLogger.Instance.error(ex);
                throw ex;
            }
        }
    }



    public static void generateResourceList(GeneratedI18nResourceList i18nResourceList, String keyPrefix, List<I18nResource> resourceList) {
        if (resourceList != null && !resourceList.isEmpty()) {
            if (!StringUtility.isBlank(keyPrefix)) {
                keyPrefix = keyPrefix + "_";
            }
            for (I18nResource item : resourceList) {
                if (item.getStringResources() != null && item.getStringResources().size() > 0) {
                    for (int i = 0; i <= item.getStringResources().size() - 1; i++) {
                        I18nResourceItem stringResourceItem = item.getStringResources().get(i);
                        if (stringResourceItem != null && !StringUtility.isNullOrEmpty(stringResourceItem.getKey())) {
                            if (stringResourceItem.getKey().contains(".")) {
                                i18nResourceList.addIfNotExistsWithKey(keyPrefix + stringResourceItem.getKey().substring(stringResourceItem.getKey().lastIndexOf(".") + 1), stringResourceItem.getValue());
                            } else {
                                i18nResourceList.addIfNotExistsWithKey(keyPrefix + stringResourceItem.getKey(), stringResourceItem.getValue());
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 生成前端国际化资源文件
     * 针对组合表单  递归生成对应的i18n文件
     *
     * @param i18nResourceList
     * @param languageJsonPath
     */
    public static void generateZhI18nJsonFile(GeneratedI18nResourceList i18nResourceList,
                                              String languageJsonPath, String fileName) {
        try {
            String languageJsonFilePath = "";

            languageJsonFilePath = FileUtility.combine(languageJsonPath, fileName);


            if (FileUtility.exists(languageJsonPath)) {
                FileUtility.deleteFile(languageJsonFilePath);
            }

            if (i18nResourceList != null && i18nResourceList.getResourceList() != null && i18nResourceList.getResourceList().size() > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append("{");

                for (int i = 0; i < i18nResourceList.getResourceList().size(); i++) {
                    GeneratedI8nResource item = i18nResourceList.getResourceList().get(i);
                    sb.append("\"" + item.getKey() + "\":" + "{\"name\":\"" + (StringUtility.isNullOrEmpty(item.getValue()) ? "" : item.getValue()) + "\"}");
                    if (i < i18nResourceList.getResourceList().size() - 1) {
                        sb.append(",");
                    }
                }
                sb.append("}");

                if (!FileUtility.exists(languageJsonPath)) {
                    FileUtility.createDirectory(languageJsonPath);
                }
                FileUtility.updateFile(languageJsonFilePath, sb.toString());
            }


        } catch (Exception ex) {
            //排除掉找不到对应的资源文件的异常
            if (ex.getMessage() != null && !ex.getMessage().contains("Can't Find Metadata")) {
                WebLogger.Instance.info(ex.getMessage() + Arrays.toString(ex.getStackTrace()), GenerateResourceManager.class.getName());
            } else {
                WebLogger.Instance.error(ex.getMessage() + Arrays.toString(ex.getStackTrace()), GenerateResourceManager.class.getName());
                throw ex;
            }
        }
    }


    public static void generateI18nJsonFile(GeneratedI18nResourceList i18nResourceList, String languageJsonPath, String fileName) {
        generateI18nJsonFile(i18nResourceList, languageJsonPath, fileName, "en");
    }


    /**
     * 生成前端国际化资源文件
     * 针对组合表单  递归生成对应的i18n文件
     *
     * @param i18nResourceList
     * @param languageJsonPath
     * @param language
     */
    public static void generateI18nJsonFile(GeneratedI18nResourceList i18nResourceList,
                                            String languageJsonPath, String fileName, String language) {
        if (i18nResourceList == null || i18nResourceList.getResourceList().isEmpty()) {
            return;
        }
        String languageJsonFilePath = "";
        if (StringUtility.isNullOrEmpty(fileName)) {
            fileName = language + ".json";
        }
        languageJsonFilePath = FileUtility.combine(languageJsonPath, fileName);

        try {
            if (FileUtility.exists(languageJsonFilePath)) {
                FileUtility.deleteFile(languageJsonFilePath);
            }

            StringBuilder sb = new StringBuilder();
            sb.append("{");

            for (int i = 0, len = i18nResourceList.getResourceList().size(); i < len; i++) {
                sb.append(i18nResourceList.getResourceList().get(i).generateI18nString());
                if (i < len - 1) {
                    sb.append(",");
                }
            }
            sb.append("}");

            if (!FileUtility.exists(languageJsonPath)) {
                FileUtility.createDirectory(languageJsonPath);
            }
            FileUtility.updateFile(languageJsonFilePath, sb.toString());
        } catch (Exception ex) {
            //排除掉找不到对应的资源文件的异常
            if (ex.getMessage() != null && !ex.getMessage().contains("Can't Find Metadata")) {
                WebLogger.Instance.info(ex.getMessage() + Arrays.toString(ex.getStackTrace()), GenerateResourceManager.class.getName());
            } else {
                WebLogger.Instance.error(ex.getMessage() + Arrays.toString(ex.getStackTrace()), GenerateResourceManager.class.getName());
            }
        }
    }


    /**
     * 生成资源项前缀
     *
     * @param source
     * @param paramaters
     * @return
     */
    public static String generateKeyPrefix(String source, String... paramaters) {
        if (paramaters == null || paramaters.length == 0) {
            return source;
        }
        String generatedParameter = "";
        for (int i = 0; i < paramaters.length; i++) {
            if (i == 0) {
                generatedParameter = paramaters[0];
            } else {
                generatedParameter = generatedParameter + "_" + paramaters[i];
            }
        }

        if (StringUtility.isNullOrEmpty(source)) {
            return generatedParameter;
        } else {
            return source + "_" + generatedParameter;
        }
    }
}
